﻿Imports System.Text

Namespace SqlServer2012
    Public Class TableFactory
        Inherits SqlServer.TableFactory

        Protected Overrides Sub CreateCore(cn As IDbConnection, ts As IEnumerable(Of Type))
            Dim fn As Func(Of String, InfoLevelEnum, IDbCommand) =
                Function(s, lv)
                    Dim cmd As IDbCommand = cn.CreateCommand
                    cmd.CommandText = s
                    Log.OnExecuteCommand.Invoke(Nothing, New CreateDbCommandEventArgs(cmd) With {.CommandInfoLevel = lv})
                    Return cmd
                End Function

            For Each item In ts
                Dim def As TableDefinition = TableDefinitionReader.Read(item, Creater)
                If def.ColumnDefinisions.Any = False Then Continue For

                fn.Invoke(Me.CreateCommandText(def), InfoLevelEnum.Warn).ExecuteNonQuery()

                'Sequence
                For Each col In (From el In def.Table.Columns Where TypeOf el.Key Is SQLServerSequenceKeyAttribute)
                    fn.Invoke(Me.CreateSequenceCommandText(col), InfoLevelEnum.Warn).ExecuteNonQuery()
                Next
            Next
        End Sub

        Private Function CreateSequenceCommandText(col As ColumnAttribute) As String
            Dim sysName As String = If(String.IsNullOrEmpty(col.Table.TableNamespace), "sysobjects", col.Table.TableNamespace & ".sysobjects")
            Dim sq = DirectCast(col.Key, SQLServerSequenceKeyAttribute)
            Dim s As New StringBuilder
            s.AppendFormat("IF EXISTS (SELECT * FROM {0} WHERE name = '{1}' AND xtype = 'SO') DROP SEQUENCE {1}", sysName, sq.SequenceName)
            s.AppendLine(";")
            s.AppendFormat("CREATE SEQUENCE {0} START WITH 1", sq.SequenceName)
            s.Append(";")

            Return s.ToString
        End Function
    End Class
End Namespace

